import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_myshop/model/category.dart';
import 'package:flutter_myshop/model/category_goods.dart';
import 'package:flutter_myshop/provide/category_goods_list.dart';
import 'package:flutter_myshop/provide/child_category.dart';
import 'package:flutter_myshop/router/application.dart';
import 'package:flutter_myshop/service/service_method.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provide/provide.dart';
import 'package:flutter_myshop/common/widget.dart';

/*
 * 分类
 */
class CategoryPage extends StatefulWidget {
  CategoryPage({Key key}) : super(key: key);

  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  // 分类数据
  BigCategoryListModel bigCategoryListModel;

  // 分离方法为了让异步方法停顿
  void _getBigCategoryListModel() {
    getCategory().then((val) {
      setState(() {
        bigCategoryListModel = BigCategoryListModel.fromJson(val['datas']);
      });
    });
  }

  @override
  void initState() {
    // 获得分类数据
    _getBigCategoryListModel();

    super.initState();
  }

  // main
  @override
  Widget build(BuildContext context) {
    // 得到展示内容
    if (bigCategoryListModel != null) {
      return Scaffold(
        appBar: AppBar(title: Text("商品分类")),
        body: Container(
          child: Row(
            children: <Widget>[
              LeftCategoryNav(
                bigCategoryList: bigCategoryListModel.bigCategoryList,
              ),
              Expanded(
                child: Column(
                  children: <Widget>[
                    RightTopNav(),
                    Expanded(child: ShowGoodsArea()),
                  ],
                ),
              )
            ],
          ),
        ),
      );
    }

    // 还未得到展示内容
    else {
      return waitWidget;
    }
  }
}

//cate 左边导航栏
class LeftCategoryNav extends StatefulWidget {
  final List<BigCategory> bigCategoryList;

  const LeftCategoryNav({Key key, this.bigCategoryList}) : super(key: key);

  @override
  _LeftCategoryNavState createState() => _LeftCategoryNavState(bigCategoryList);
}

class _LeftCategoryNavState extends State<LeftCategoryNav> {
  /// 数据区
  // 选择的坐标
  int selecedIndex;
  // 总的分类数据List
  final List<BigCategory> bigCategoryList;
  // 存储大分类的所有name
  List<String> bigCategoryNameList;
  // 分类商品数据
  CategoryGoodListModel categoryGoodListModel;

  ///  构造函数
  _LeftCategoryNavState(this.bigCategoryList);

  // 得到分页内容数据
  void _getCategoryPageContent(String bigCategoryId) async {
    dynamic val =
        await getCategoryPageContent(bigCategoryId: bigCategoryId, page: 0);
    categoryGoodListModel = CategoryGoodListModel.fromJson(val['data']);
  }

  //main
  @override
  Widget build(BuildContext context) {
    // 获取各个大分类的name
    bigCategoryNameList = bigCategoryList.map((item) {
      return item.bigCategoryName;
    }).toList();
    return _leftNav();
  }

  //cate  组件区
  // 整合小方格形成导航栏
  Widget _leftNav() {
    return Container(
      width: ScreenUtil().setWidth(66),
      child: ListView.builder(
        scrollDirection: Axis.vertical,
        itemCount: bigCategoryNameList.length,
        itemBuilder: (context, index) {
          return _smallRoom(index);
        },
      ),
    );
  }

  // 小方格基本组件
  Widget _smallRoom(int index) {
    // 用于判定是否选中
    bool isClick = false;

    isClick = (index == selecedIndex) ? true : false;

    return Container(
      decoration: BoxDecoration(
        border: Border(
          top: BorderSide(color: Colors.black12, width: 0.9),
          right: BorderSide(color: Colors.black12, width: 0.5),
        ),
        color: isClick ? Colors.pink : Colors.white,
      ),
      height: ScreenUtil().setHeight(33),
      width: ScreenUtil().setWidth(66),
      child: InkWell(
        onTap: () async {
          print('点击了大分类......');
          setState(() {
            selecedIndex = index;
          });

          // 添加小分类都需要的'全部'按键
          List<SmallCategory> newSmallCategoryList = [
            SmallCategory(smallCategoryId: '0', smallCategoryName: "全部")
          ];
          newSmallCategoryList.addAll(bigCategoryList[index].smallCategoryList);

          //联动子类导航栏:将小分类的List传过去
          Provide.value<ChildCategoryProvider>(context)
              .setSmallCategoryList(newSmallCategoryList);

          // 改变状态中的index
          Provide.value<ChildCategoryProvider>(context)
              .setSmallCategoryIndex(0);
          // 存储状态大分类Id
          Provide.value<ChildCategoryProvider>(context)
              .setBigCategoryId(bigCategoryList[index].bigCategoryId);

          // 根据分类请求数据
          await _getCategoryPageContent(bigCategoryList[index].bigCategoryId);

          //联动子类内容区,点击大分类,商品内容刷新
          Provide.value<CategoryGoodListProvider>(context)
              .setGoodsList(categoryGoodListModel.goods);

          // 将Page清零
          Provide.value<CategoryGoodListProvider>(context).setPage(0);
        },
        child: Container(
            padding: EdgeInsets.all(10),
            alignment: Alignment.centerLeft,
            child: Text(
              "${bigCategoryNameList[index]}",
              style: TextStyle(
                fontSize: ScreenUtil().setSp(10),
              ),
            )),
      ),
    );
  }
}

//cate 右边顶部分类导航
class RightTopNav extends StatefulWidget {
  RightTopNav({Key key}) : super(key: key);

  @override
  _RightTopNavState createState() => _RightTopNavState();
}

class _RightTopNavState extends State<RightTopNav> {
  @override
  Widget build(BuildContext context) {
    return Container(
      child: _rightTopNav(),
    );
  }

  // 整合小方格形成导航栏
  Widget _rightTopNav() {
    return Provide<ChildCategoryProvider>(
      builder: (context, child, childCategory) {
        return Container(
          height: ScreenUtil().setHeight(30),
          alignment: Alignment.topLeft,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: childCategory.smallCategoryList.length,
            itemBuilder: (context, index) {
              return _smallRoom(index,
                  childCategory.smallCategoryList[index].smallCategoryName);
            },
          ),
        );
      },
    );
  }

  // 小方格基本组件
  Widget _smallRoom(int index, String samllCategoryName) {
    List<SmallCategory> smallCategoryList =
        Provide.value<ChildCategoryProvider>(context).smallCategoryList;

    // 获取大分类Id
    String bigCategoryId =
        Provide.value<ChildCategoryProvider>(context).bigCategoryId;

    bool isClick = false;
    isClick = (index ==
            Provide.value<ChildCategoryProvider>(context).smallCategoryIndex)
        ? true
        : false;

    return Container(
      decoration: BoxDecoration(
          border: Border(
        bottom: BorderSide(color: Colors.black12, width: 0.9),
      )),
      child: InkWell(
        onTap: () {
          print('点击了小分类......');
          // 改变状态中的index
          Provide.value<ChildCategoryProvider>(context)
              .setSmallCategoryIndex(index);

          // 存储选择的小分类ID
          Provide.value<ChildCategoryProvider>(context)
              .setSmallCategoryId(smallCategoryList[index].smallCategoryId);

          // 修改展示商品
          getCategoryPageContent(
                  bigCategoryId: bigCategoryId,
                  smallCategoryId: smallCategoryList[index].smallCategoryId,
                  page: 0)
              .then((val) {
            // Model 化获取数据
            CategoryGoodListModel goodListModel =
                CategoryGoodListModel.fromJson(val['data']);
            // 修改展示商品
            Provide.value<CategoryGoodListProvider>(context)
                .setGoodsList(goodListModel.goods);
          });
          // 将Page清零
          Provide.value<CategoryGoodListProvider>(context).setPage(0);
        },
        child: Container(
            padding: EdgeInsets.fromLTRB(
                ScreenUtil().setWidth(5),
                ScreenUtil().setHeight(10),
                ScreenUtil().setWidth(5),
                ScreenUtil().setHeight(5)),
            alignment: Alignment.center,
            child: Text(
              "$samllCategoryName",
              style: TextStyle(
                  fontSize: ScreenUtil().setSp(10),
                  color: (isClick) ? Colors.red : Colors.black),
            )),
      ),
    );
  }
}

//cate 商品展示
class ShowGoodsArea extends StatefulWidget {
  ShowGoodsArea({Key key}) : super(key: key);

  @override
  _ShowGoodsAreaState createState() => _ShowGoodsAreaState();
}

class _ShowGoodsAreaState extends State<ShowGoodsArea> {
  // 一个的展示框
  Widget _oneBox(Good item, context) {
    return Container(
      height: ScreenUtil().setHeight(157),
      width: ScreenUtil().setWidth(106),
      child: InkWell(
          onTap: () {
            // log
            print("点击了列表商品......");
            Application.router.navigateTo(context, "/detail?id=${item.id}");
          },
          child: Column(
            children: <Widget>[
              Expanded(
                child: Image.network(
                  item.image,
                  fit: BoxFit.fill,
                ),
              ),
              // name展示
              Container(
                padding: EdgeInsets.fromLTRB(5, 10, 5, 10),
                child: Text('${item.name}'),
              ),
              //  价格展示
              Container(
                padding: EdgeInsets.fromLTRB(3, 10, 5, 10),
                child: Row(
                  children: <Widget>[
                    Text('¥ ${item.price}  '),
                    Text(
                      '¥ ${item.noDiscountedPrice}',
                      style: TextStyle(
                          decoration: TextDecoration.lineThrough,
                          color: Colors.black26),
                    ),
                  ],
                ),
              )
            ],
          )),
    );
  }

  // main
  @override
  Widget build(BuildContext context) {
    return EasyRefresh(
      // 无新增商品处理
      footer: ClassicalFooter(
        bgColor: Colors.white,
        textColor: Colors.blue,
        loadText: '加载更多',
        loadReadyText: '准备加载',
        loadingText: '正在加载',
        loadedText: '加载完成',
        noMoreText: '已经是最后了',
        loadFailedText: '加载失败',
        showInfo: false,
        completeDuration: Duration(seconds: 1),
        enableInfiniteLoad: false,
      ),
      // 上拉刷新
      onLoad: () {
        // 获取信息
        getCategoryPageContent(
                bigCategoryId:
                    Provide.value<ChildCategoryProvider>(context).bigCategoryId,
                smallCategoryId: Provide.value<ChildCategoryProvider>(context)
                    .smallCategoryId,
                page: Provide.value<CategoryGoodListProvider>(context).page)
            .then((val) {
          // 有商品可以添加
          if (val['data'] != null) {
            // Model 化获取数据
            CategoryGoodListModel goodListModel =
                CategoryGoodListModel.fromJson(val['data']);
            // 修改展示商品
            Provide.value<CategoryGoodListProvider>(context)
                .addGoodsList(goodListModel.goods);
            // 增加Page
            Provide.value<CategoryGoodListProvider>(context).IncreasePage();
          }
          // 没有商品添加
          else {
            Fluttertoast.showToast(
                msg: "没有更多商品",
                toastLength: Toast.LENGTH_SHORT,
                gravity: ToastGravity.CENTER,
                timeInSecForIos: 1,
                backgroundColor: Colors.blue,
                textColor: Colors.white,
                fontSize: 16.0);
          }
        });

        return null;
      },
      child: Container(
        child:
            Provide<CategoryGoodListProvider>(builder: (context, child, data) {
          return Wrap(
            children: data.categoryGoodList.map((item) {
              return _oneBox(item, context);
            }).toList(),
          );
        }),
      ),
    );
  }
}
